class Api::V1::ProductExpressesController < Api::V1::BaseController
  before_action :authenticate_request!

  def index
    @product_express = apply_scopes(ProductExpress).all
    @product_express = paginate(@product_express)
    render json: @product_express, meta: paginate_meta(@product_express)
  end

  def create
    begin
      @product_express = ProductExpress.new(create_params)
      authorize @product_express
      @product_express.save!
      render json: @product_express, status: 201
    rescue ActiveRecord::StatementInvalid
      @product_express.errors.add(:exec_error, 'Contact Administrator')
      error_render(@product_express, 403)
    rescue => err
      error_render(err.record, 403)
    end
  end

  def batch_create
    begin
      pes = []
      create_params[:attributes].each do |pe|
        pes << ProductExpress.new(pe)
      end

      ProductExpress.import! pes
      render status: 201
    rescue RecordInvalid
      render status: 403
    rescue
      render status: 403
    end
  end

  def show
    @product_express = ProductExpress.find(params[:id])
    render json: @product_express, status: 200
  end

  def update
    begin
      @product_express = ProductExpress.find(params[:id])
      @product_express.update_attributes!(create_params)
      render json: @product_express, status: 200
    rescue => err
      error_render(err.record, 403)
    end
  end

  def destroy
    begin
      @product_express = ProductExpress.find(params[:id])
      @product_express.destroy!
      render status: 204
    rescue ActiveRecord::RecordNotFound
      render status: 404
    rescue => err
      error_render(err.record, 403)
    end
  end

  private
  def create_params
    params_parse(params)
  end

  def batch_params
    params.require(:data).permit(:type, :id, attributes: [])
  end
end
